from flask import Blueprint, request
from app import app
from app.service.user_service import UserService
from app.service.upload_service import UploadService
from app.util.result import Result

"""
用户模块路由定义
该模块处理所有与用户相关的HTTP请求
"""

# 创建用户模块的蓝图
user_bp = Blueprint('user', __name__)


@user_bp.route('/register', methods=['POST'])
def register():
    """
    用户注册接口
    Request Body:
        - username: 用户名
        - password: 密码
        - role: 用户角色
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    register_data = request.get_json()
    success, message = UserService.register(
        register_data['username'],
        register_data['password'],
        register_data['role']
    )
    if not success:
        return Result.fail(message=message)
    return Result.success()


@user_bp.route('/login', methods=['POST'])
def login():
    """
    用户登录接口
    Request Body:
        - username: 用户名
        - password: 密码
    Returns:
        - 成功: {"code": 1,"data": {"id": 用户ID, "token": JWT令牌, "role": 用户角色}}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    login_data = request.get_json()
    success, message, data = UserService.login(
        login_data['username'],
        login_data['password']
    )
    if not success:
        return Result.fail(message=message)
    return Result.success(data=data)


@user_bp.route('/info', methods=['GET'])
def info():
    """
    获取用户信息接口
    Headers:
        - Authorization: JWT令牌
    Returns:
        - 成功: {"code": 1,"data": 用户信息}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    user_id = app.payload['id']
    success, message, data = UserService.get_user_info(user_id)
    if not success:
        return Result.fail(message=message)
    return Result.success(data=data)


@user_bp.route('/update', methods=['PUT'])
def update():
    """
    更新用户信息接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - username: 用户名
        - age: 年龄
        - gender: 性别
        - phone: 电话
        - email: 邮箱
        - avatar: 头像URL
        - description: 个人描述
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    update_data = request.get_json()
    user_id = app.payload['id']
    success, message = UserService.update_user_info(user_id, update_data)
    if not success:
        return Result.fail(message=message)
    return Result.success()


@user_bp.route('/avatar/upload', methods=['POST'])
def avatar_upload():
    """
    上传用户头像接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - file: 图片文件
    Returns:
        - 成功: {"code": 1,"data": {"avatar": 头像URL}}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    res = UploadService.upload(request.files)
    if res:
        return Result.success(data={
            'avatar': res
        })
    else:
        return Result.fail(message="上传失败")


@user_bp.route('/updatePassword', methods=['PUT'])
def update_password():
    """
    修改用户密码接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - oldPassword: 旧密码
        - newPassword: 新密码
    Returns:
        - 成功: {"code": 1}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    update_data = request.get_json()
    user_id = app.payload['id']
    success, message = UserService.update_password(
        user_id,
        update_data['oldPassword'],
        update_data['newPassword']
    )
    if not success:
        return Result.fail(message=message)
    return Result.success()


@user_bp.route('/getUserAvatar', methods=['GET'])
def get_user_avatar():
    """
    获取用户头像接口
    Headers:
        - Authorization: JWT令牌
    Returns:
        - 成功: {"code": 1, "data": {"avatar": 头像URL, "role": 用户角色}}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    user_id = app.payload['id']
    success, message, data = UserService.get_user_avatar(user_id)
    if not success:
        return Result.fail(message=message)
    return Result.success(data=data)


@user_bp.route('/getAdminList', methods=['GET'])
def get_admin_list():
    """
    获取管理员列表接口
    Headers:
        - Authorization: JWT令牌
    params:
        - page: 页码
        - size: 每页数量
    Returns:
        - 成功: {"code": 1, "data": {"total": 总数据个数, "list": 管理员列表}}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    uid = app.payload['id']
    page = request.args.get('page', default=1, type=int)
    size = request.args.get('size', default=10, type=int)
    success, message, data = UserService.get_admin_list(uid, page, size)
    if not success:
        return Result.fail(message=message)
    return Result.success(data=data)

@user_bp.route('/toggleAdminStatus', methods=['PUT'])
def toggle_admin_status():
    """
    切换管理员状态接口
    Headers:
        - Authorization: JWT令牌
    Args:
        - id: 用户id
        - status: 状态(1:正常, 0:禁用)
    Returns:
        - 成功: {"code": 1}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    uid = app.payload['id']
    data=request.get_json()

    user_id = data['id']
    status = data['status']
    if user_id is None or status is None:
        return Result.fail(message="参数错误")
    success, message = UserService.toggle_admin_status(uid, user_id, status)
    if not success:
        return Result.fail(message=message)
    return Result.success()

@user_bp.route('/deleteAdmin', methods=['DELETE'])
def delete_admin():
    """
    删除管理员接口
    Headers:
        - Authorization: JWT令牌
    Args:
        - id: 用户id
    Returns:
        - 成功: {"code": 1}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    uid = app.payload['id']
    user_id = request.args.get('id', default=None)
    if not user_id:
        return Result.fail(message="参数错误")
    success, message = UserService.delete_admin(uid, user_id)
    if not success:
        return Result.fail(message=message)
    return Result.success()

@user_bp.route('/isSuperAdmin', methods=['GET'])
def is_super_admin():
    """
    判断是否是超级管理员接口
    Headers:
        - Authorization: JWT令牌
    Returns:
        - 成功: {"code": 1}
        - 失败: {"code": 0}
    """
    uid = app.payload['id']
    success= UserService.is_super_admin(uid)
    return Result.success() if success else Result.fail()

@user_bp.route('/addAdmin', methods=['POST'])
def add_admin():
    """
    添加管理员接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - username: 用户名
        - password: 密码
    Returns:
        - 成功: {"code": 1}
        - 失败: {"code": 0, "message": "错误信息"}
    """
    uid = app.payload['id']
    data = request.get_json()
    username = data['username']
    password = data['password']
    success, message = UserService.add_admin(uid, username, password)
    if not success:
        return Result.fail(message=message)
    return Result.success()